package com.spiro.ssl;

import com.spiro.common.BaseJavaClient;
import com.spiro.common.Configuration;
import com.spiro.common.tutorial.Calculator;
import org.apache.thrift.TException;
import org.apache.thrift.protocol.TBinaryProtocol;
import org.apache.thrift.protocol.TProtocol;
import org.apache.thrift.transport.TSSLTransportFactory;
import org.apache.thrift.transport.TTransport;
import org.apache.thrift.transport.TTransportException;

import java.util.ArrayList;
import java.util.List;

public class SslBioClient extends BaseJavaClient {

    public SslBioClient(String host, int port) {
        super(host, port);
    }

    @Override
    public Calculator.Client connectAndGet() throws TException {
        TSSLTransportFactory.TSSLTransportParameters params
                = new TSSLTransportFactory.TSSLTransportParameters();

        String truststoreFilename = Configuration.getInstance()
                .getConf("ssl.truststore.filename");
        String truststorePassword = Configuration.getInstance()
                .getConf("ssl.truststore.password");
        params.setTrustStore(truststoreFilename, truststorePassword, "SunX509", "JKS");

        transport = TSSLTransportFactory.getClientSocket(this.host, this.port, 0, params);

        TProtocol protocol = new TBinaryProtocol(transport);
        return new Calculator.Client(protocol);
    }

    public static List<SslBioClient> getInstances(int n, String host, int port) {
        List<SslBioClient> clients = new ArrayList<>(n);

        for (int i = 0; i < n; i++) {
            clients.add(new SslBioClient(host, port));
        }

        return clients;
    }

}
